<?php

namespace App\Http\Controllers\Util;

use App\Services\OSS;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
class UploadController extends Controller
{
    public function upload(Request $request)
    {
        //获取上传的文件
        $file = $request->file('file');
//        dd($file);
        //获取上传图片的临时地址
        $tmppath = $file->getRealPath();
        //生成文件名
        $fileName = str_random(5) . $file->getFilename() . time() .date('ymd') . '.' . $file->getClientOriginalExtension();
        //拼接上传的文件夹路径(按照日期格式1810/17/xxxx.jpg)
        $pathName = date('Y-m/d').'/'.$fileName;
        //上传图片到阿里云OSS
        OSS::publicUpload('fiproject', $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]);
        //获取上传图片的Url链接
        $Url = OSS::getPublicObjectURL('fiproject', $pathName);
        // 返回状态给前端，Laravel框架会将数组转成JSON格式
        return ['code' => 0, 'msg' => '上传成功', 'data' => ['src' => $Url]];
    }

    /**
     * 检测是否为图片
     *
     * @param $file		上传文件
     *
     * @return bool		true/flase
     */
    protected function isImage ( $file )
    {
        //strtolower 扩展名不区分大小写
        $ext = strtolower ( $file->getClientOriginalExtension () );
        //检测上传文件是否为图片
        return in_array ( $ext , [ 'jpg' , 'jpeg' , 'png' , 'gif' ] );

    }

    //显示已上传图片列表
    public function lists ()
    {
        //查找当前用户上传的所有附件
        $data = Attachment::where('user_id',auth ('admin')->user ()->id)->paginate(2);
        //将其转为数组
        $db = $data->toArray();
        //循环给每一个数据中追加一个下标为url的元素
        foreach($db['data'] as $k=>$v){
            $db['data'][$k]['url'] = $v['path'];
        }
        //dd($db);
        //返回数据，数据格式参考hdjs中图片列表
        return [
            'code'=>0,
            'data'=>$db['data'],
            'page'=>$data->links() . ''
        ];
    }
}
